package com.xunyu.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinyu.shopping_common.entity.Admin;
import com.xinyu.shopping_common.entity.AdminRole;
import com.xinyu.shopping_common.entity.Permission;
import com.xinyu.shopping_common.service.IAdminService;
import com.xunyu.shopping_admin_service.mapper.AdminMapper;
import com.xunyu.shopping_admin_service.mapper.AdminRoleMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@DubboService
@Transactional //事务注解
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Override
    public void add(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void update(Admin admin) {
        adminMapper.updateById(admin);
    }

    @Override
    public void delete(Long aid) {

        LambdaQueryWrapper<AdminRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminRole::getAid,aid);
        //删除管理员角色中间表的中间数据
        adminRoleMapper.delete(queryWrapper);
        //删除管理与
        adminMapper.deleteById(aid);
    }

    @Override
    public Admin findById(Long aid) {
        return adminMapper.findById(aid);
    }

    @Override
    public Page<Admin> search(int page, int size) {

        //创建分页对象
        Page<Admin> adminPage = new Page<>();

        //分页搜索
        adminMapper.selectPage(adminPage,null);

        return adminPage;
    }

    @Override
    public void updateRoleToAdmin(Long aid, Long[] rids) {

        //1.删除原有的角色数据
        LambdaQueryWrapper<AdminRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminRole::getAid,aid);
        //删除管理员角色中间表的中间数据
        adminRoleMapper.delete(queryWrapper);

        //2.添加新的角色数据
        for (Long rid : rids) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAid(aid);
            adminRole.setRid(rid);

            //插入管理员角色信息
            adminRoleMapper.insert(adminRole);
        }

    }

    @Override
    public Admin findByAdminName(String username) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,username);
        return adminMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Permission> findAllPermission(String username) {
        return adminMapper.findAllPermission(username);
    }
}
